package com.dl.base.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiInfo
import android.net.wifi.WifiManager
import kotlinx.coroutines.suspendCancellableCoroutine
import java.net.Inet4Address
import java.net.NetworkInterface
import java.net.SocketException
import kotlin.coroutines.resume

/**
 * Created by LHG on 2017/4/17.
 */
object NetUtil {


    /**
     * 获得IP地址，分为两种情况，一是wifi下，二是移动网络下，得到的ip地址是不一样的
     */
    fun getIPAddress(context: Context): String? {
        val info: NetworkInfo? =
            (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).getActiveNetworkInfo()
        if (info != null && info.isConnected) {
            when (info.type) {
                ConnectivityManager.TYPE_MOBILE -> { //当前使用2G/3G/4G网络
                    try {
                        //Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
                        val en = NetworkInterface.getNetworkInterfaces()
                        while (en.hasMoreElements()) {
                            val intf = en.nextElement()
                            val enumIpAddr = intf.inetAddresses
                            while (enumIpAddr.hasMoreElements()) {
                                val inetAddress = enumIpAddr.nextElement()
                                if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                                    return inetAddress.getHostAddress()
                                }
                            }
                        }
                    } catch (e: SocketException) {
                        e.printStackTrace()
                    }
                }
                ConnectivityManager.TYPE_WIFI -> { //当前使用无线网络
                    val wifiManager: WifiManager =
                        context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                    val wifiInfo: WifiInfo = wifiManager.connectionInfo
                    //调用方法将int转换为地址字符串
                    return intIP2StringIP(wifiInfo.ipAddress)
                }
                ConnectivityManager.TYPE_ETHERNET -> {
                    return ethernetIp
                }
            }
        } else {
            //当前无网络连接,请在设置中打开网络
        }
        return null
    }

    // 获取有线网IP
    private val ethernetIp: String
        private get() {
            try {
                val en = NetworkInterface.getNetworkInterfaces()
                while (en.hasMoreElements()) {
                    val intf = en.nextElement()
                    val enumIpAddr = intf.inetAddresses
                    while (enumIpAddr.hasMoreElements()) {
                        val inetAddress = enumIpAddr.nextElement()
                        if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
                            return inetAddress.getHostAddress()
                        }
                    }
                }
            } catch (ex: SocketException) {
            }
            return "0.0.0.0"
        }

    /**
     * 将得到的int类型的IP转换为String类型
     *
     * @param ip
     * @return
     */
    fun intIP2StringIP(ip: Int): String {
        return ((ip and 0xFF).toString() + "." +
                ((ip shr 8) and 0xFF) + "." +
                ((ip shr 16) and 0xFF) + "." +
                (ip shr 24 and 0xFF))
    }

    /*获取mac地址有一点需要注意的就是android 6.0版本后，以下注释方法不再适用，不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址，这是googel官方为了加强权限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法来获得mac地址。*/
    //        String macAddress= "";
//        WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        macAddress = wifiInfo.getMacAddress();
//        return macAddress;
    val macAddress: String
        get() {
            /*获取mac地址有一点需要注意的就是android 6.0版本后，以下注释方法不再适用，不管任何手机都会返回"02:00:00:00:00:00"这个默认的mac地址，这是googel官方为了加强权限管理而禁用了getSYstemService(Context.WIFI_SERVICE)方法来获得mac地址。*/
            //        String macAddress= "";
//        WifiManager wifiManager = (WifiManager) MyApp.getContext().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        macAddress = wifiInfo.getMacAddress();
//        return macAddress;
            var macAddress: String? = null
            val buf = StringBuffer()
            var networkInterface: NetworkInterface? = null
            try {
                networkInterface = NetworkInterface.getByName("eth1")
                if (networkInterface == null) {
                    networkInterface = NetworkInterface.getByName("wlan0")
                }
                if (networkInterface == null) {
                    return "02:00:00:00:00:02"
                }
                val addr = networkInterface.hardwareAddress
                for (b: Byte in addr) {
                    buf.append(String.format("%02X:", b))
                }
                if (buf.isNotEmpty()) {
                    buf.deleteCharAt(buf.length - 1)
                }
                macAddress = buf.toString()
            } catch (e: SocketException) {
                e.printStackTrace()
                return "02:00:00:00:00:02"
            }
            return macAddress
        }

    suspend fun ping(sourceIp: String) = suspendCancellableCoroutine<Boolean> {
        val ip = sourceIp.split("://").toTypedArray()[1]
        val ipStr = ip.split(":").toTypedArray()[0]
        val exec = Runtime.getRuntime().exec("ping -c 1 -w 3 $ipStr")
        it.resume(exec.waitFor() == 0)
    }
}